<?php

namespace App\Models\Cashier;

use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
    protected $guarded = [];

    //每个商品属于某个品牌
    public function brand()
    {
        return $this->belongsTo('App\Models\Cashier\Brand');
    }

    //每个商品属于一个分类
    public function category()
    {
        return $this->belongsTo('App\Models\Cashier\Category');
    }

    //每个商品属于一个供应商
    public function apply()
    {
        return $this->belongsTo('App\Models\Cashier\Apply');
    }

    //每个商品属于一个门店
    public function store()
    {
        return $this->belongsTo('App\Models\Cashier\Store');
    }


    static function all_products($request)
    {
        $where = function ($query) use ($request) {
            //按商品名称
            if ($request->has('keyword') and $request->keyword != '') {
                $search = "%" . $request->keyword . "%";
                $query->where('name', 'like', $search);
            }

            //按品牌
            if ($request->has('brand_id') and $request->brand_id != '-1') {
                $query->where('brand_id', $request->brand_id);
            }

            //按门店
            if ($request->has('store_id') and $request->store_id != '-1') {
                $query->where('store_id', $request->store_id);
            }

            //按分类
            if ($request->has('category_id') and $request->category_id != '-1') {
                $query->where('category_id', $request->category_id);
            }

            //按照时间搜索
            if ($request->has('created_at') and $request->created_at != '') {
                $time = explode(" ~ ", $request->input('created_at'));
                $start_time = $time[0] . ' 00:00:00'; //这里单引号前面要打一空格
                $end_time = $time[1] . ' 23:59:59';
                $query->whereBetween('created_at', [$start_time, $end_time]);
            }
        };
        $products = self::with('brand', 'category', 'store')->where($where)->orderBy('sort_order', 'desc')->paginate(env('pageSize'));
        return $products;
    }


}
